"use client";
import { Button, Form, Input, InputNumber, message, Select } from "antd";
import React, { useEffect, useState } from "react";
import { aiGenerateQuestionsUsingPost } from "@/api/questionController";
import { listQuestionBankByPageUsingPost } from "@/api/questionBankController";
import "./index.css";

interface Props {}

/**
 * AI 生成题目页面
 * @param props
 * @constructor
 */
const AiGenerateQuestionPage: React.FC<Props> = (props) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [questionBanks, setQuestionBanks] = useState<API.QuestionBank[]>([]);
  const [bankLoading, setBankLoading] = useState(true);

  // 加载题库列表
  useEffect(() => {
    const loadQuestionBanks = async () => {
      try {
        const res = await listQuestionBankByPageUsingPost({
          pageSize: 100, // 一次加载足够多的题库
          current: 1,
        });
        // @ts-ignore
        if (res.data?.records) {
          // @ts-ignore
          setQuestionBanks(res.data.records);
        }
      } catch (error: any) {
        message.error("题库加载失败: " + error.message);
      } finally {
        setBankLoading(false);
      }
    };
    loadQuestionBanks();
  }, []);

  /**
   * 提交
   */
  const doSubmit = async (values: API.QuestionAIGenerateRequest) => {
    const hide = message.loading("正在生成题目");
    setLoading(true);
    try {
      await aiGenerateQuestionsUsingPost(values);
      hide();
      message.success("题目生成成功");
    } catch (error: any) {
      hide();
      message.error("操作失败，" + error.message);
    }
    setLoading(false);
  };

  return (
    <div id="aiGenerateQuestionPage">
      <h2>AI 生成题目</h2>
      <Form form={form} style={{ marginTop: 24 }} onFinish={doSubmit}>
        <Form.Item
          label="目标题库"
          name="questionBankId"
          rules={[{ required: true, message: "请选择题库" }]}
        >
          <Select
            loading={bankLoading}
            placeholder="请选择题目所属题库"
            options={questionBanks.map((bank) => ({
              label: bank.title,
              value: bank.id,
            }))}
          />
        </Form.Item>

        <Form.Item
          label="题目方向"
          name="questionType"
          rules={[{ required: true, message: "请输入题目方向" }]}
        >
          <Input placeholder="例如：Java 多线程、React 组件开发" />
        </Form.Item>

        <Form.Item
          label="题目数量"
          name="number"
          rules={[{ required: true, message: "请填写题目数量" }]}
          initialValue={10}
        >
          <InputNumber
            style={{ width: "100%" }}
            min={1}
            max={50}
            precision={0}
          />
        </Form.Item>

        <Form.Item>
          <Button
            loading={loading}
            style={{ width: 180 }}
            type="primary"
            htmlType="submit"
          >
            开始生成
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};
export default AiGenerateQuestionPage;
